#知识检索模块
import json
import os

class KnowledgeRetriever:
    def __init__(self, kb_path='rust_knowledge_base/rust_docs_sample.json'):
        self.kb_path = kb_path
        if os.path.exists(self.kb_path):
            with open(self.kb_path, 'r', encoding='utf-8') as f:
                self.docs = json.load(f)
        else:
            self.docs = []

    def retrieve(self, question, topk=3):
        # 简单关键词匹配，返回相关文档
        results = []
        for doc in self.docs:
            if any(word in doc['content'] for word in question.split()):
                results.append(doc)
        return results[:topk] if results else self.docs[:topk] 